{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import os\n",
    "from skimage import io\n",
    "import numpy as np\n",
    "from sklearn import neighbors\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 28\n",
    "# Gray threshold 灰度阈值\n",
    "color = 200 / 255\n",
    "\n",
    "featurePath = \"D:\\\\手写数字\\\\train\\\\\"\n",
    "labelPath = \"D:\\\\手写数字\\\\train.txt\"\n",
    "\n",
    "labelmap = {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "#加载图片标签数据\n",
    "def loadLabelData():\n",
    "    for line in open(labelPath, 'r'):\n",
    "        kv = line.strip().split(\" \")\n",
    "        labelmap[kv[0]] = kv[1]\n",
    "      \n",
    "        \n",
    "loadLabelData()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "加载数据完成\n"
     ]
    }
   ],
   "source": [
    "#  读取训练图片并保存\n",
    "def GetTrainPicture(path):\n",
    "    files = os.listdir(path)\n",
    "    Picture = np.zeros([len(files), N ** 2])\n",
    "    label = np.zeros([len(files), 10])  # 用于存放对应的标签one-hot\n",
    "    # 循环所有图片文件\n",
    "    for i, item in enumerate(files):\n",
    "        #  读取这个图片并转为灰度值\n",
    "        img = io.imread(path + item, as_gray=True)\n",
    "        # 清除噪音\n",
    "        img[img > color] = 1\n",
    "        # 将图片存入矩阵\n",
    "        Picture[i, 0:N ** 2] = img.reshape(N ** 2)\n",
    "        # 将图片的名字存入矩阵\n",
    "        label[i][int(labelmap[item])] = 1.0\n",
    "    return Picture,label\n",
    "\n",
    "#返回目录下的所有图片\n",
    "pic, label = GetTrainPicture(featurePath)\n",
    "print(\"加载数据完成\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模型训练完成\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\n",
    "# 构建KNN分类器：设置查找算法以及邻居点 数量(k)值。\n",
    "# KNN是一种懒惰学习法，没有学习过程，只在预测时去查找最近邻的点，\n",
    "# 数据集的输入就是构建KNN分类器的过程\n",
    "knn = neighbors.KNeighborsClassifier(algorithm='kd_tree', n_neighbors=3)\n",
    "knn.fit(pic, label)\n",
    "print(\"模型训练完成\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "加载数据完成\n"
     ]
    }
   ],
   "source": [
    "#加载测试集数据\n",
    "testpath = \"D:\\\\手写数字\\\\test2\\\\\"\n",
    "\n",
    "testpic, tetlabel = GetTrainPicture(testpath)\n",
    "print(\"加载数据完成\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始测试\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "总数据量: 30000 错误数据量: 309  正确率: 0.9897\n测试完成\n"
     ]
    }
   ],
   "source": [
    "print(\"开始测试\")\n",
    "res = knn.predict(testpic)  # 对测试集进行预测\n",
    "error_num = np.sum(res != tetlabel)  # 统计预测错误的数目\n",
    "num = len(pic)  # 测试集的数目\n",
    "\n",
    "print(\"总数据量:\", num, \"错误数据量:\", error_num, \" 正确率:\", 1 - error_num / float(num))\n",
    "print(\"测试完成\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前数字为:0\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# 使用模型\n",
    "\n",
    "\n",
    "Picture = np.zeros(N ** 2 + 1)\n",
    "#Read the picture and turn RGB to grey 读取这个图片并转为灰度值\n",
    "img = io.imread(\"D:\\\\手写数字\\\\train\\\\783.jpg\", as_gray=True)\n",
    "# print(img)\n",
    "# # Clear the noise 清除噪音\n",
    "img[img > color] = 1\n",
    "\n",
    "# 手写数字识别\n",
    "pre = knn.predict(img.reshape([1, N ** 2]))\n",
    "l = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n",
    "r = l[pre[0] == 1][0]\n",
    "print(\"当前数字为:%d\" % r)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
